package com.unidentifiable.wechat.util;

import cn.hutool.http.HttpUtil;
import com.unidentifiable.wechat.accesstoken.AccessTokenInfo;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 信息工具类
 * @author unidentifiable
 * @date 2021-02-28
 */
public class MessageUtil {

    /**
     * 解析微信发来的请求（XML）
     *
     * @param request 请求
     * @return map
     * @throws Exception 异常
     */
    public static Map<String, String> parseXml(HttpServletRequest request) {
        // 将解析结果存储在HashMap中
        Map<String, String> map = new HashMap<>(16);
        // 从request中取得输入流
        try (InputStream inputStream = request.getInputStream()) {
            System.out.println("获取输入流");
            // 读取输入流
            SAXReader reader = new SAXReader();
            Document document = reader.read(inputStream);
            // 得到xml根元素
            Element root = document.getRootElement();
            // 得到根元素的所有子节点
            List<Element> elementList = root.elements();

            // 遍历所有子节点
            for (Element e : elementList) {
                System.out.println(e.getName() + "|" + e.getText());
                map.put(e.getName(), e.getText());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return map;
    }

    /**
     * 获取用户详情
     * @param openId 用户id
     * @return 用户详情
     */
    public static String getUserInfo(String openId) {
        String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + AccessTokenInfo.accessToken.getTokenName() + "&openid=" + openId + "&lang=zh_CN";
        return HttpUtil.get(url);
    }
}
